package com.tian.scroll.view_move.fragment;

import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import com.tian.scroll.R;
import com.tian.scroll.databinding.FragmentMoveViewScrollBinding;

/**
 * @author tiansongtao, Email:769001510@qq.com, created on 2021/1/19 9:55
 * <p>
 * scrollTo/scrollBy 移动控件内容
 */
public class ScrollViewFragment extends Fragment {

    private FragmentMoveViewScrollBinding b;

    private int preX, preY;
    private boolean scrollBy = true;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        b = DataBindingUtil.inflate(inflater, R.layout.fragment_move_view_scroll, container, false);
        b.clContext.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    preX = (int) event.getRawX();
                    preY = (int) event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    int y = (int) event.getRawY();
                    int x = (int) event.getRawX();
                    int dy = y - preY;
                    int dx = x - preX;
                    b.clContext.scrollBy(-dx, -dy);
                    preY = y;
                    preX = x;
                    break;
            }

            return !scrollBy;
        });
        b.mbtScrollBy.setOnClickListener(v -> {
            b.btScroll.setScrollBy(true);
            scrollBy = true;
        });
        b.mbtScrollTo.setOnClickListener(v -> {
            b.btScroll.setScrollBy(false);
            scrollBy = false;
        });
        return b.getRoot();
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        menu.clear();
        super.onCreateOptionsMenu(menu, inflater);
    }
}